package com.google.devrel.example.android.protips.mvp;

import java.text.MessageFormat;
import java.util.UUID;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.wifi.WifiManager;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.devrel.example.android.protips.R;

public class TrackPresenter {

	private ITrackView _view;

	public TrackPresenter(ITrackView view) {
		_view = view;
	}
	
	private static final String PREF_UNIQUE_ID = "PREF_UNIQUE_ID";
	
	public View getRootView(LayoutInflater inflater, ViewGroup container) {
		if (UUID.randomUUID().getLeastSignificantBits() % 2 == 0) {
			// Inflate the layout for this fragment
			return inflater.inflate(R.layout.track_fragment, container,
					false);
		} else {
			return inflater.inflate(R.layout.track_fragment_exp, container,
					false);
		}
	}
	
	public void fillViewContent(Context context) {
		
		// telephony
		TelephonyManager telman = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		if (telman!=null) {
			_view.setDeviceId(MessageFormat.format("{0}: {1}", 
					context.getResources().getString(R.string.track_deviceId), telman.getDeviceId()));
		}
		
		// wifi
		WifiManager wifiman = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		if (wifiman!=null) {
			String str = "N/A";
			if (wifiman.getConnectionInfo()!=null) {
				str = wifiman.getConnectionInfo().getMacAddress();
			}
			_view.setMacAddress(MessageFormat.format("{0}: {1}",
					context.getResources().getString(R.string.track_macAddress), str));
		}
		
		// android_id
		{
			_view.setAndroidId(MessageFormat.format("{0}: {1}",
					context.getResources().getString(R.string.track_androidId),
					Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID)));
		}
		
		// unique install
		SharedPreferences sp = context.getSharedPreferences(PREF_UNIQUE_ID, Context.MODE_PRIVATE);
		String uniqueId = sp.getString(PREF_UNIQUE_ID, null);
		if (uniqueId==null) {
			uniqueId = UUID.randomUUID().toString();
			sp.edit().putString(PREF_UNIQUE_ID, uniqueId).commit();
		}
		_view.setUniqueInstall(MessageFormat.format("{0}: {1}",
				context.getResources().getString(R.string.track_uniqueInst), uniqueId));
	}
}
